package org.jerry.virtualoperator.task;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.kevinsawicki.http.HttpRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Date 2020/11/24
 * @Created JerryZeng
 */

@Slf4j
@Component
public class VsmsTemplateReportSchedule {

    @Autowired
    ThreadPoolTaskExecutor fileReadExecutor;
    @Autowired
    Cache<Long, String> templateBackCache;

    static ObjectMapper jackson = new ObjectMapper();

    @SneakyThrows
//    @Scheduled(cron = "0 0/1 * * * ? ")
    public void report() {
        ConcurrentMap<Long, String> templates = templateBackCache.asMap();
        if(templates.size() == 0) {
            log.info("no template");
            return;
        }

        final CountDownLatch latch = new CountDownLatch(templates.size());
        templates.forEach((id, url) ->
            fileReadExecutor.execute(() -> {
                Map<String, Object> map = new HashMap<>(2);
                map.put("templateId", id);
                map.put("status", "PASSED");

                try {
                    String body = HttpRequest.post(url)
                            .contentType(MediaType.APPLICATION_JSON_VALUE)
                            .acceptJson()
                            .send(jackson.writeValueAsString(map))
                            .body();
                    log.info("template reported back: {}", body);
                } catch (JsonProcessingException e) {
                    log.error(e.getMessage(), e);
                } finally {
                    latch.countDown();
                }
            })
        );

        latch.await(30, TimeUnit.SECONDS);
        templates.clear();
    }
}
